﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;

namespace CustomAuthorization.MinimumAgeAuthorize
{
//#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
    public class MinimumAgePolicyProvider : IAuthorizationPolicyProvider
    {
        const string MinimumAgePolicyPrefix = "MinimumAge";

        public DefaultAuthorizationPolicyProvider FallBackPolicyProvider { get; }

        public MinimumAgePolicyProvider(IOptions<AuthorizationOptions> options)
        {
            FallBackPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
        }

        public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        {
            return FallBackPolicyProvider.GetDefaultPolicyAsync();
        }

        public Task<AuthorizationPolicy?> GetFallbackPolicyAsync()
        {
           return FallBackPolicyProvider.GetFallbackPolicyAsync();
        }

        public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
        {
            if(policyName.StartsWith(MinimumAgePolicyPrefix,StringComparison.OrdinalIgnoreCase)&& int.TryParse(policyName.Substring(MinimumAgePolicyPrefix.Length), out var age))
            {
                var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme);
                policy.AddRequirements(new MinimumAgeRequirement(age));
                return Task.FromResult<AuthorizationPolicy?>(policy.Build());
            }
            return Task.FromResult<AuthorizationPolicy?>(null);
        }
    }
}
